package mark.tom.sail;

import android.util.Base64;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

import static mark.tom.sail.C.UTF_8;
import static mark.tom.sail.Util.log_e;

class Base64DataSecurity implements DataSecurity {

    private final LogInterceptor logInterceptor;

    Base64DataSecurity(@NonNull LogInterceptor logInterceptor) {
        this.logInterceptor = logInterceptor;
    }

    @Override
    public String encrypt(@NonNull String data) {
        String result = null;
        try {
            result = Base64.encodeToString(data.getBytes(UTF_8), Base64.DEFAULT).replaceAll("\\n", "");
        } catch (Exception ex) {
            log_e(logInterceptor, ex.getMessage());
        }
        return result;
    }

    @Override
    public String decrypt(@NonNull String data) {
        String result = null;
        try {
            result = new String(Base64.decode(data, Base64.DEFAULT), UTF_8);
        } catch (Exception ex) {
            log_e(logInterceptor, ex.getMessage());
        }
        return result;
    }

    @Override
    public List<String> decrypt(@NonNull List<String> data) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            String tmp = decrypt(data.get(i));
            if (tmp != null) {
                result.add(tmp);
            }
        }
        return result.size() == 0 ? null : result;
    }
}
